package com.cherrish.demo.block2;

import com.cherrish.demo.block1.StringUtil;
import lombok.Data;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author cherrish
 * @time 2019-02-15 11:45
 * @name Block
 * @desc:
 */
@Data
public class Block {
    /**是这个块在整个链中的位置*/

    private int index;

    /**显而易见就是块生成时的时间戳*/

    private String timestamp;

    /**虚拟资产。我们要记录的数据*/

    private int vac;

    /**是这个块通过 SHA256 算法生成的散列值*/

    private String hash;

    /**指向前一个块的 SHA256 散列值*/

    private String prevHash;

    private ArrayList<Block> blockchain;

    public static String calculateHash(Block block) {

        String record = (block.getIndex()) + block.getTimestamp() + (block.getVac()) + block.getPrevHash();
        return StringUtil.applySha256(record);//SHA256.crypt(record);

    }

    public static Block generateBlock(Block oldBlock, int vac) {

        Block newBlock = new Block();

        newBlock.setIndex(oldBlock.getIndex() + 1);

        newBlock.setTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        newBlock.setVac(vac);

        newBlock.setPrevHash(oldBlock.getHash());

        newBlock.setHash(calculateHash(newBlock));

        return newBlock;

    }

    public static boolean isBlockValid(Block newBlock, Block oldBlock) {

        if (oldBlock.getIndex() + 1 != newBlock.getIndex()) {

            return false;

        }

        if (!oldBlock.getHash().equals(newBlock.getPrevHash())) {

            return false;

        }

        if (!calculateHash(newBlock).equals(newBlock.getHash())) {

            return false;

        }

        return true;

    }

    public void replaceChain(ArrayList<Block> newBlocks) {

        if (newBlocks.size() > blockchain.size()) {

            blockchain = newBlocks;

        }

    }

}
